package com.wandong.cinema.service.impl;

import com.wandong.cinema.entity.Movie;
import com.wandong.cinema.service.MovieService;
import com.wandong.cinema.util.IdGenerator;
import com.wandong.cinema.util.InputUtil;
import com.wandong.cinema.util.LogUtil;
import com.wandong.cinema.entity.Hall;
import com.wandong.cinema.entity.Show;
import com.wandong.cinema.service.HallService;
import com.wandong.cinema.service.ShowService;
import com.wandong.cinema.service.TicketService;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class MovieServiceImpl implements MovieService {
    // 存储所有影片，影片ID作为键
    public static final Map<String, Movie> MOVIE_MAP = new ConcurrentHashMap<>();

    @Override
    public void addMovie() {
        try {
            System.out.println("\n=== 添加影片 ===");
            System.out.print("请输入影片名称: ");
            String name = InputUtil.inputString();
            System.out.print("请输入导演: ");
            String director = InputUtil.inputString();
            System.out.print("请输入主演: ");
            String actor = InputUtil.inputString();
            System.out.print("请输入影片类型: ");
            String type = InputUtil.inputString();
            System.out.print("请输入剧情简介: ");
            String introduction = InputUtil.inputString();
            System.out.print("请输入片长(分钟): ");
            int duration = InputUtil.inputInteger();
            System.out.print("请输入评分(0-10): ");
            double score = InputUtil.inputDouble();
            System.out.print("请输入上映日期(yyyy-MM-dd): ");
            String releaseDate = InputUtil.inputString();
            
            // 验证评分范围
            if (score < 0 || score > 10) {
                System.out.println("评分必须在0-10分之间");
                return;
            }
            
            String movieId = IdGenerator.generateMovieId();
            Movie movie = new Movie(movieId, name, director, actor, introduction, 
                                   duration, score, type, releaseDate);
            
            MOVIE_MAP.put(movieId, movie);
            LogUtil.log("添加影片：" + name + ", ID: " + movieId);
            System.out.println("影片添加成功，影片ID: " + movieId);
        } catch (Exception e) {
            System.out.println("添加影片失败: " + e.getMessage());
        }
    }

    @Override
    public void deleteMovie() {
        System.out.println("\n=== 删除影片 ===");
        try {
            System.out.print("请输入要删除的影片ID: ");
            String movieId = InputUtil.inputString();
            
            if (!MOVIE_MAP.containsKey(movieId)) {
                System.out.println("影片不存在");
                return;
            }
            
            // 实际实现中应先检查是否有排片，有排片则不能删除
            Movie movie = MOVIE_MAP.remove(movieId);
            LogUtil.log("删除影片：" + movie.getName() + ", ID: " + movieId);
            System.out.println("影片删除成功");
        } catch (Exception e) {
            System.out.println("删除影片失败: " + e.getMessage());
        }
    }

    @Override
    public void updateMovie() {
        System.out.println("\n=== 修改影片 ===");
        System.out.print("请输入要修改的影片ID: ");
        String movieId = InputUtil.inputString();
        
        if (!MOVIE_MAP.containsKey(movieId)) {
            System.out.println("影片不存在");
            return;
        }
        
        Movie movie = MOVIE_MAP.get(movieId);
        System.out.println("当前影片信息: " + movie);
        
        System.out.print("请输入新名称(回车不修改): ");
        String newName = InputUtil.inputString();
        if (!newName.isEmpty()) {
            movie.setName(newName);
        }
        
        System.out.print("请输入新评分(0-10, 回车不修改): ");
        String scoreStr = InputUtil.inputString();
        if (!scoreStr.isEmpty()) {
            double newScore = Double.parseDouble(scoreStr);
            if (newScore >= 0 && newScore <= 10) {
                movie.setScore(newScore);
            } else {
                System.out.println("评分必须在0-10分之间，未修改评分");
            }
        }
        
        // 可以根据需要添加更多可修改的字段
        
        MOVIE_MAP.put(movieId, movie);
        LogUtil.log("修改影片：" + movie.getName() + ", ID: " + movieId);
        System.out.println("影片修改成功");
    }

    @Override
    public void queryMovies() {
        System.out.println("\n=== 影片查询 ===");
        System.out.println("1-查询所有影片 2-按名称查询 3-按类型查询 4-查询场次座位信息");
        int choice = InputUtil.inputInteger();

        List<Movie> result = new ArrayList<>();

        switch (choice) {
            case 1:
                result.addAll(MOVIE_MAP.values());
                break;
            case 2:
                System.out.print("请输入影片名称: ");
                String name = InputUtil.inputString();
                for (Movie movie : MOVIE_MAP.values()) {
                    if (movie.getName().contains(name)) {
                        result.add(movie);
                    }
                }
                break;
            case 3:
                System.out.print("请输入影片类型: ");
                String type = InputUtil.inputString();
                for (Movie movie : MOVIE_MAP.values()) {
                    if (movie.getType().contains(type)) {
                        result.add(movie);
                    }
                }
                break;
            case 4:
                // 查询指定电影和场次的座位信息
                queryShowSeats();
                return; // 直接返回，不执行下面的显示逻辑
            default:
                System.out.println("无效选择");
                return;
        }

        if (result.isEmpty()) {
            System.out.println("没有找到符合条件的影片");
            return;
        }

        System.out.println("\n查询结果:");
        for (Movie movie : result) {
            System.out.println(movie);
        }
    }

    /**
     * 查询指定电影和场次的座位信息
     */
    private void queryShowSeats() {
        try {
            // 1. 输入电影名称查询电影
            System.out.print("请输入影片名称: ");
            String movieName = InputUtil.inputString();

            // 查找匹配的电影
            List<Movie> matchedMovies = new ArrayList<>();
            for (Movie movie : MOVIE_MAP.values()) {
                if (movie.getName().contains(movieName)) {
                    matchedMovies.add(movie);
                }
            }

            if (matchedMovies.isEmpty()) {
                System.out.println("未找到匹配的影片");
                return;
            }

            // 如果有多部匹配的电影，让用户选择
            Movie selectedMovie = null;
            if (matchedMovies.size() == 1) {
                selectedMovie = matchedMovies.getFirst();
                System.out.println("找到影片: " + selectedMovie.getName());
            } else {
                System.out.println("找到多部匹配的影片，请选择:");
                for (int i = 0; i < matchedMovies.size(); i++) {
                    System.out.println((i + 1) + ". " + matchedMovies.get(i).getName());
                }
                System.out.print("请选择(输入序号): ");
                int movieChoice = InputUtil.inputInteger();
                if (movieChoice < 1 || movieChoice > matchedMovies.size()) {
                    System.out.println("无效选择");
                    return;
                }
                selectedMovie = matchedMovies.get(movieChoice - 1);
            }

            // 2. 根据电影ID查询场次
            ShowService showService = new ShowServiceImpl();
            List<Show> shows = showService.getShowsByMovieId(selectedMovie.getMovieId());

            if (shows.isEmpty()) {
                System.out.println("该影片暂无场次安排");
                return;
            }

            // 显示场次信息并让用户选择
            System.out.println("\n该影片的场次信息:");
            for (int i = 0; i < shows.size(); i++) {
                Show show = shows.get(i);
                System.out.println((i + 1) + ". " + show);
            }

            System.out.print("请选择场次(输入序号): ");
            int showChoice = InputUtil.inputInteger();
            if (showChoice < 1 || showChoice > shows.size()) {
                System.out.println("无效选择");
                return;
            }

            Show selectedShow = shows.get(showChoice - 1);

            // 3. 查询座位信息
            displayShowSeats(selectedShow);
        } catch (Exception e) {
            System.out.println("查询座位信息失败: " + e.getMessage());
        }
    }

    /**
     * 显示场次座位信息
     * @param show 场次信息
     */
    private void displayShowSeats(Show show) {
        try {
            // 获取放映厅信息
            HallService hallService = new HallServiceImpl();
            Hall hall = hallService.getHallById(show.getHallId());

            if (hall == null) {
                System.out.println("未找到放映厅信息");
                return;
            }

            int rowCount = hall.getRowCount();
            int colCount = hall.getColCount();

            // 获取已售座位
            ShowService showService = new ShowServiceImpl();
            TicketService ticketService = new TicketServiceImpl(showService);
            List<String> soldSeats = ticketService.getSoldSeats(show.getShowId());

            // 显示座位信息
            System.out.println("\n场次座位信息:");
            System.out.println("放映厅: " + hall.getName());
            System.out.println("总座位数: " + (rowCount * colCount));

            int freeSeatCount = rowCount * colCount - soldSeats.size();
            System.out.println("空闲座位数: " + freeSeatCount);

            // 显示座位布局
            System.out.println("\n座位布局 (o表示空闲, x表示已售):\n");

            // 打印列号
            System.out.print("   ");
            for (int j = 1; j <= colCount; j++) {
                System.out.printf("%2d ", j);
            }
            System.out.println();

            // 打印座位
            for (int i = 1; i <= rowCount; i++) {
                // 打印行号
                System.out.printf("%2d ", i);
                for (int j = 1; j <= colCount; j++) {
                    String seatId = i + "," + j;
                    if (soldSeats.contains(seatId)) {
                        System.out.print(" x ");
                    } else {
                        System.out.print(" o ");
                    }
                }
                System.out.println();
            }
        } catch (Exception e) {
            System.out.println("显示座位信息失败: " + e.getMessage());
        }
    }

    @Override
    public Movie getMovieById(String movieId) {
        return MOVIE_MAP.get(movieId);
    }
    
    // 添加获取所有电影的实现方法
    @Override
    public List<Movie> getAllMovies() {
        return new ArrayList<>(MOVIE_MAP.values());
    }
}